/**
 * 
 */
package com.hzutitech.aqfxgk.android;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author HKP 2011-6-17
 * 
 */
public class FileselectionDialog extends Dialog implements android.view.View.OnClickListener {

	private ListView list;
	ArrayAdapter<String> Adapter;
	ArrayList<String> arr = new ArrayList<String>();

	FileselectionDialogListener listener;

	Context context;
	private String path;

	private TextView title;
	private Button home, back, ok;

	private String[] fileType = null;

	/**
	 * @param context
	 * @param type
	 *            值为1表示创建打开目录类型的对话框�?为创建保存文件到目录类型的对话框
	 * @param fileType
	 *            要过滤的文件类型,null表示只�?择目�?
	 * @param resultPath
	 *            点OK按钮返回的结果，目录或�?目录+文件�?
	 */
	public FileselectionDialog(Context context, String[] fileType, String resultPath, FileselectionDialogListener listener) {
		super(context);
		this.context = context;
		this.fileType = fileType;
		this.path = resultPath;
		this.listener = listener;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Dialog#dismiss()
	 */
	@Override
	public void dismiss() {
		super.dismiss();
		listener.onOkClick(title.getText().toString());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Dialog#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.select_dialog);

		path = getRootDir();
		arr = (ArrayList<String>) getDirs(path);
		Adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arr);

		list = (ListView) findViewById(R.id.list_dir);
		list.setAdapter(Adapter);

		list.setOnItemClickListener(lvLis);

		home = (Button) findViewById(R.id.btn_home);
		home.setOnClickListener(this);

		back = (Button) findViewById(R.id.btn_back);
		back.setOnClickListener(this);

		ok = (Button) findViewById(R.id.btn_ok);
		ok.setOnClickListener(this);

		title.setText(path);
	}

	// 动�?更新ListView
	Runnable add = new Runnable() {

		@Override
		public void run() {
			arr.clear();
			// 必须得用这种方法为arr赋�?才能更新
			List<String> temp = getDirs(path);
			for (int i = 0; i < temp.size(); i++) {
				arr.add(temp.get(i));
			}
			Adapter.notifyDataSetChanged();
		}
	};

	private OnItemClickListener lvLis = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			String temp = (String) arg0.getItemAtPosition(arg2);
			// System.out.println("OnItemClick path1:"+path);
			if (temp.equals("..")) {
				path = getSubDir(path);
			} else if (path.equals("/")) {
				path += temp;
			} else {
				path += temp;
			}
			title.setText(path);
			File isDir = new File(path);
			System.out.println(path + " : " + isDir.isDirectory());
			if (!isDir.isDirectory()) {
				dismiss();
			}
			Handler handler = new Handler();
			handler.post(add);
		}
	};

	private List<String> getDirs(String ipath) {
		System.out.println("TAG DIR " + ipath);
		List<String> file = new ArrayList<String>();
		File[] myFile = new File(ipath).listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathName) {
				if (fileType == null || fileType.length < 1) {
					return true;
				} else {
					String suffix = pathName.getName().substring(pathName.getName().lastIndexOf(".") + 1);
					for (String filterSuffix : fileType) {
						if (suffix.equalsIgnoreCase(filterSuffix)) {
							return false;
						}
					}
				}
				return false;
			}
		});
		if (myFile == null || myFile.length < 1) {
			file.add("..");
		} else
			for (File f : myFile) {
				// 过滤目录
				String tempf = f.toString();
				if (f.isDirectory()) {
					int pos = tempf.lastIndexOf("/");
					String subTemp = tempf.substring(pos, tempf.length());
					file.add(subTemp);
				} else {
					int pos = tempf.lastIndexOf("/");
					String subTemp = tempf.substring(pos + 1, tempf.length());
					file.add(subTemp);
				}
				// 过滤知道类型的文�?
				if (f.isFile() && fileType != null) {
					for (int i = 0; i < fileType.length; i++) {
						int typeStrLen = fileType[i].length();
						String fileName = f.getPath().substring(f.getPath().length() - typeStrLen);
						if (fileName.toLowerCase().equals(fileType[i])) {
							file.add(f.toString().substring(path.length() + 1, f.toString().length()));
						}
					}
				}
			}
		return file;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		if (v.getId() == home.getId()) {
			path = getRootDir();
			title.setText(path);
			Handler handler = new Handler();
			handler.post(add);
		} else if (v.getId() == back.getId()) {
			path = getSubDir(path);
			title.setText(path);
			Handler handler = new Handler();
			handler.post(add);
		} else if (v.getId() == ok.getId()) {
			dismiss();
		}
		Toast.makeText(context, path, Toast.LENGTH_SHORT).show();
	}

	private String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存�?
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取根目�?
		}
		if (sdDir == null) {
			// Toast.makeText(context,
			// "No SDCard inside!",Toast.LENGTH_SHORT).show();
			return null;
		}
		return sdDir.toString();

	}

	private String getRootDir() {
		String root = "/";

		path = getSDPath();
		if (path == null)
			path = "/";

		return root;
	}

	private String getSubDir(String path) {
		String subpath = null;

		int pos = path.lastIndexOf("/");

		if (pos == path.length()) {
			path = path.substring(0, path.length() - 1);
			pos = path.lastIndexOf("/");
		}

		subpath = path.substring(0, pos);

		if (pos == 0)
			subpath = path;

		return subpath;
	}
}
